<template>
  <div>
    <el-form ref="roleForm" size="small" :model="entity" :rules="rules"  @submit.native.prevent label-width="120px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="entity.roleName" @keyup.enter.native="onSubmit" ref="roleName" placeholder="角色名称" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="onSubmit">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import request from '@/utils/request'
export default {
  props:{
    entityId : {type : Number, default: 0}
  },
  data() {
    return {
      entity: {
        roleName: '',
      },
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
      }
    }
  },
  mounted() {
    this.loadEntity();
    this.$nextTick(()=>{
      this.$refs.roleName.focus()
    })
  },
  methods: {
    loadEntity(){
      if(this.entityId > 0){
        request({ url: '/sys/role/getrole', data: {id : this.entityId} }).then( res =>{
          this.entity = res.data
        })
      }
    },
    onSubmit(){
      this.$refs['roleForm'].validate((valid) => {
        if(valid){
          request({
            url: '/sys/role/addeditrole',
            data: this.entity
          }).then( res =>{
            if(res.code === "200"){
              this.$message.success(res.msg)
              this.$emit('update:visible', false);  //关闭弹窗
              //触发事件总线，让列表界面更新数据
              this.entityId > 0 ? this.$EventBus.$emit("roleedit", {}):this.$EventBus.$emit("roleadd", {})
            }else{
              this.$message.error(res.msg);
            }
          })
        }else{
          console.log('error submit!!');
          return false;
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
